import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
const request = axios.create({
  baseURL: 'http://likede2-admin.itheima.net/likede'
})

// 请求拦截器
request.interceptors.request.use(function (config) {
  if (store.state.user.token) {
    config.headers.Authorization = store.state.user.token
  }
  return config
}, function (err) {
  return Promise.reject(err)
})

// 响应拦截器
request.interceptors.response.use(function (response) {
  return response.data
}, function (err) {
  if (err.response && err.response.data && err.response.status === 401) {
    store.dispatch('user/logout')
    router.push('/login')
  } else {
    Message.error(err.message)
  }
  return Promise.reject(err)
})

export default request
